package com.chy.vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.chy.commonutils.Result;
import com.chy.servicebase.exceptionhandler.GuLiException;
import com.chy.vod.service.VodService;
import com.chy.vod.utils.ConstantVodUtils;
import com.chy.vod.utils.InitVodClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Api(tags = "阿里云视频点播微服务")
@RestController
@RequestMapping("/eduvod/video")
@CrossOrigin
public class VodController {

    @Autowired
    private VodService vodService;

    @ApiOperation(value = "上传视频到阿里云")
    @PostMapping("uploadAlyVideo")
    public Result uploadAlyVideo(@ApiParam(name = "file", value = "文件", required = true) MultipartFile file) {
        // 返回上传视频id
        String videoId = vodService.uploadVideoAly(file);
        return Result.ok().data("videoId",videoId);
    }

    @ApiOperation(value = "根据视频id删除阿里云视频")
    @DeleteMapping("removeAlyVideo/{id}")
    public Result removeAlyVideo(@ApiParam(name = "id", value = "云端视频id", required = true)
                                     @PathVariable String id)
    {
        vodService.removeVideo(id);
        return Result.ok().message("删除视频成功");
    }

    @ApiOperation(value = "删除多个阿里云视频")
    @DeleteMapping("delete-batch")
    public Result deleteBatch(@ApiParam(name = "videoIdList", value = "云端视频id", required = true)
                                  @RequestParam("videoIdList") List<String> videoIdList)
    {
        vodService.removeMoreAlyVideo(videoIdList);
        return Result.ok();
    }

    @ApiOperation(value = "根据视频id获取视频凭证")
    @GetMapping("getPlayAuth/{id}")
    public Result getPlayAuth(@PathVariable String id) {
        try {
            // 创建初始化对象
            DefaultAcsClient client = InitVodClient.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);
            // 创建获取凭证request
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            // 向request设置视频id
            request.setVideoId(id);
            // 调用方法得到凭证
            GetVideoPlayAuthResponse response = client.getAcsResponse(request);
            // 得到播放凭证
            String playAuth = response.getPlayAuth();
            // 返回结果
            return Result.ok().data("playAuth",playAuth);
        } catch (Exception e) {
            throw new GuLiException(20001,"获取凭证失败");
        }
    }
}
